Filling a Drop Down List (ComboBox)


Tip
Each item in a drop down list control has a text and a data. Use the data of each item to store the primary key of a table. The drop down list is usually known as ComboBox.

Problem 1
Create a Wintempla project called CategoryDropList to display the categories in a drop down list control (use a dialog application). Insert a drop down list control as shown; set the name of the control to ddCategory.

Step A
Edit the connection string in the stdafx.h file as shown below.

stdafx.h
...
#define DSN L"dsn_MyDatabase"
#define USERNAME L"root"
#define PASSWORD L"123"
#define CONNECTION_STRING L"DRIVER={SQL Server};server=SELO\\SQLEXPRESS;database=best_buy;Trusted_Connection=yes"


Step B
Drag the SELECT drop down list template from the menu: Tools>Add Wintempla Item...> Clipboard code > SQL Application Programming > SELECT dropDownList CategoryDropList.cpp file.

Step C
Edit the CategoryDropList.cpp file as shown.

CategoryDropList.cpp
void CategoryDropList::Window_Open(Win::Event& e)
{
     Sql::SqlConnection conn;
     try
     {
          //conn.OpenSession(DSN, USERNAME, PASSWORD); //Control Panel>Administrative Tools>Data Sources (ODBC)>Create dsn_myDatabase
          conn.OpenSession(hWnd, CONNECTION_STRING);
          conn.ExecuteSelect(L"SELECT category_id, descr FROM category", 100, ddCategory);
     }
     catch (Sql::SqlException e)
     {
          this->MessageBox(e.GetDescription(), L"Error", MB_OK | MB_ICONERROR);
     }
     ddCategory.SelectedIndex = 0;
}

CategoryDropList

Problem 2
Repeat the last problem using C#, named your project CategoryDropListS. Create a C# Windows Form Application. Drag a Drop Down a ComboBox (Drop Down List).

Step A
Add the class ListItem: Project > Add Class... > C# Class .

ListItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CategoryDropListS
{
     public class ListItem
     {
          private int valueData;
          private string displayData;

          public ListItem(int valueData, string displayData)
          {
                this.valueData = valueData;
               this.displayData = displayData;
          }
          public string DisplayData
          {
               get
               {
                    return displayData;
               }
          }

          public int ValueData
          {
               get
               {
                    return valueData;
               }
          }
     }
}

Step B
Add the class DatabaseInfo: Project > Add Class... > C# Class .

DatabaseInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CategoryDropListS
{
     class DatabaseInfo
     {
          public static string GetConnectionInfo()
          {
               return "server=selo\\SQLExpress;database=best_buy;Trusted_Connection=yes";
          }
     }
}

Step C
Double click the form to create the Load event handler function. Then, edit the Form1.cs file as shown

Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; // <<<<<<<<<<<<<< ADD THIS LINE

namespace CategoryDropListS
{
     public partial class Form1 : Form
     {
          public Form1()
          {
               InitializeComponent();
          }

          private void Form1_Load(object sender, EventArgs e)
          {
               SqlConnection conn = new SqlConnection(DatabaseInfo.GetConnectionInfo());
               SqlCommand cmd = null;
               SqlDataReader reader = null;
               this.comboBox1.DisplayMember = "displayData";
               //this.comboBox1.DisplayMember = "Item2"
               this.comboBox1.ValueMember = "valueData";
               //this.comboBox1.ValueMember = "Item1";
               this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
               //this.comboBox1.DataSource = dataSet;

               try
               {
                    conn.Open();
                    cmd = new SqlCommand("SELECT category_id, descr FROM category", conn);
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                         comboBox1.Items.Add(new ListItem(reader.GetInt32(0), reader["descr"].ToString()));
                         //comboBox1.Items.Add(new Tupple<int, string>(reader.GetInt32(0), reader["descr"].ToString()));
                    }
               }
               catch (SqlException ex)
               {
                    MessageBox.Show(ex.Message);
               }
               finally
               {
                    reader.Close();
                    conn.Close();
                    comboBox1.SelectedIndex = 0;
               }
          }
     }
}

CategoryDropListS

Tip
There are several methods to fill a drop down list. For instance, a SqlAdapter or OdbcDataAdapter can be used to fill a data set, then the DataSource member of the drop down list can be set to the data set.

Problem 3
Create a Wintempla Web application called CategoryDropListWeb usinc C++. Add a drop down list control as shown and set the name of the control to ddCategory.

ddCategory

Step A
Edit the connection string in the stdafx.h file.

stdafx.h
...
#define DSN L"dsn_MyDatabase"
#define USERNAME L"root"
#define PASSWORD L"123"
#define CONNECTION_STRING L"DRIVER={SQL Server};server=SELO\\SQLEXPRESS;database=best_buy;Trusted_Connection=yes"


Step B
Edit the Index.cpp file as shown below.

CategoryDropListWeb.cpp
#include "stdafx.h" //_____________________________________________ Index.cpp
#include "Index.h"

void Index::Window_Open(Web::HttpConnector& h)
{
     Sql::SqlConnection conn;
     try
     {
          //conn.OpenSession(DSN, USERNAME, PASSWORD); //Control Panel>Administrative Tools>Data Sources (ODBC)>Create dsn_myDatabase
          conn.OpenSession(NULL, CONNECTION_STRING);
          conn.ExecuteSelect(L"SELECT category_id, descr FROM category", 100, ddCategory);
     }
     catch (Sql::SqlException e)
     {
          this->MessageBox(e.GetDescription(), L"Error", MB_OK | MB_ICONERROR);
     }
     if (h.FirstTime == true)
     {
          ddCategory.SelectedIndex = 2;
     }
}

CategoryListWeb

FirstTime

Each time a web page is open, the function Window_Open is called. In some cases, it is necessary to set a selection for default in some GUI elements. In the previous problem, the program pre-selects item 3 (index 2) by default. Observe that the selection must be set only the first time the web page is open; in future calls, we must respect whatever the user has been selected.
Cada vez que se abre una página web, la función Window_Open es llamada. En algunos, casos es necesario fijar una selección por defecto en algunos elementos GUI. Por ejemplo, en el programa previo se pre-selecciona el artículo 3 (índice 2) por defecto. Observe que sólo se desea fijar la selección la primera vez que la página se abra; en llamadas futuras se debe respetar la selección del usuario.

Problem 4
Publish the web application called CategoryDropListWeb to a web server, see Wintempla > Publishing a Web Site use Anonymous Access.
Publique la aplicación llamada CategoryDropListWeb en un servidor web, vea Wintempla > Publishing a Web Site use Acceso Anónimo.

Problem 5
Create an ASP.NET Empty Web application called CategoryDropListWebS using C#. Then, add a new web form using the menu: Project>Add New Item... . Set the name of the web form to index.aspx.

Step A
Change the view to Design Mode and insert a Drop Down List control as shown. Drag the control from the toolbox and drop it inside the body.

ASPDesignMode

Step B
Edit the index.aspx.cs file as shown.

index.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient; // <<<<<<<<<<<<<<< ADD THIS LINE
using System.Data; // <<<<<<<<<<<<<<< ADD THIS LINE

namespace CategoryDropListWebS
{
     public partial class Index : System.Web.UI.Page
     {
          protected void Page_Load(object sender, EventArgs e)
          {
               SqlConnection conn = new SqlConnection(DatabaseInfo.GetConnectionInfo());
               SqlCommand cmd = null;

               try
               {
                    conn.Open();
                    cmd = new SqlCommand("SELECT category_id, descr FROM category", conn);
                    DataSet dataSet = new DataSet();
                    SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
                    dataAdapter.Fill(dataSet);
                    this.DropDownList1.DataSource = dataSet;
                    this.DropDownList1.DataValueField = "category_id";
                    this.DropDownList1.DataTextField = "descr";
                    this.DropDownList1.DataBind();
               }
               catch (SqlException ex)
               {
                    //this.LabelError.Text = ex.Message;
               }
               finally
               {
                    conn.Close();
               }
          }
     }
}

indexaspx

Problem 6
Add a new Web IIS application to the CategoryDropList solution to create a Dual Application. Review the instructions at: Wintempla > Introduction > Dual Calculator before working on this problem. Do not forget to edit the SQL connection string by editing the stdafx.h file in both projects.

CategoryDropList.cpp
...
void CategoryDropList::Window_Open(Win::Event& e)
{
     //________________________________________________________ ddCategory
     CategoryDropListDual::Window_Open(*this, NULL);
     ddCategory.SelectedIndex = 2;
}

Index.cpp
...
void Index::Window_Open(Web::HttpConnector& h)
{
     CategoryDropListDual::Window_Open(*this, &h);
     if (h.FirstTime == true) ddCategory.SelectedIndex = 2;
}

CategoryDropListDual.cpp
...
void CategoryDropListDual::Window_Open(Sys::IWindow& window, Web::HttpConnector* h)
{
     Sql::SqlConnection conn;
     try
     {
          //conn.OpenSession(DSN, USERNAME, PASSWORD); //Control Panel>Administrative Tools>Data Sources (ODBC)>Create dsn_myDatabase
          conn.OpenSession(window, CONNECTION_STRING);
          conn.ExecuteSelect(L"SELECT category_id, descr FROM category", 100, ddCategoryD);
     }
     catch (Sql::SqlException e)
     {
          window.MessageBox(e.GetDescription(), L"Error", MB_OK | MB_ICONERROR);
     }
}

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home